import { Alert, AutoComplete, Button, message, Statistic, Tag } from 'antd';
import React, {
  useState,
  useRef
} from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type {
  ProColumns,
  ActionType
} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import ProCard from '@ant-design/pro-card';
import { queryRule, selectStudent, classroomExport } from './service';
import { Link } from "react-router-dom"
import { downloadFile } from '@/utils/utils';
import moment from 'moment';
import { AUTH_TOKEN } from '@/utils/request';
import { baseUrl } from '@/utils/httpUrl';
const TableList: React.FC<{}> = (props: any) => {
  const attendanceMap = {
    1: {
      color: 'blue',
      label: '出勤'
    },
    2: {
      color: 'red',
      label: '缺勤'
    }
  }
  const { classroomId } = props.location.query
  const actionRef = useRef<ActionType>();
  const [className, setClassName] = useState()
  const [options, setOptions] = useState<{ value: string }[]>([]);
  const [uid, setUid] = useState<any>()
  const onSelect = (data: any, option: any) => {
    setUid(option.id)
  };
  const onSearch = async (key: string) => {
    const data = await selectStudent(key)
    function getStudentSearchOptions(keys: any, data: any) {
      return !keys ? [] : data.result.map((item: { uid: any; nickname: any; phone: any }) => ({
        id: item.uid,
        label: (item.nickname || '') + `  (${item.phone})`,
        value: item.nickname + `  (${item.phone})`
      }))
    }
    const options = getStudentSearchOptions(key, data)
    setOptions(options);
  };
  const classroomExportHandler = async function (className) {
    if (!classroomId) {
      message.error('请选择或者输入课程id')
      return
    }
    const url = await classroomExport({ classroomId: String(classroomId) })
    downloadFile(`条目训练情况-${className}-${moment(new Date().getTime()).format('YYYY-MM-DD HH-mm-ss')}`, url, '.xls')
  }
  const durationHandler = (duration) => {
    if (!duration) {
      return
    }
    duration = Math.ceil(Number(duration) / 60)
    const h = Number.parseInt(duration / 60) + '小时'
    const m = Number.parseInt(duration % 60) + '分钟'
    if (h) {
      return `${h + m}`
    } else {
      return m
    }

  }
  const columns: ProColumns<{}>[] = [
    {
      title: '用户名',
      dataIndex: 'key',
      hideInTable: true,
      renderFormItem: (text, props) =>
        <AutoComplete
          options={options}
          onSelect={onSelect}
          onSearch={onSearch}
          placeholder="请选择"
        />,
    },
    {
      title: '用户id',
      dataIndex: 'uid',
      hideInSearch: true,
    },
    {
      title: '用户昵称',
      dataIndex: 'nickname',
      hideInSearch: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      hideInSearch: true,
    },
    {
      title: '班级',
      dataIndex: 'groupName',
      hideInSearch: true
    },
    {
      title: '辅导老师',
      dataIndex: 'teacherName',
      hideInSearch: true
    },
    {
      title: '是否出勤',
      dataIndex: 'attendance',
      hideInSearch: true,
      render: (attendance: any, record) => (
        record.attendance ? <Tag color={attendanceMap[attendance].color} >
          {attendanceMap[attendance].label}
        </Tag> : "-"
      ),
    },
    {
      title: '到课时长',
      dataIndex: 'duration',
      hideInSearch: true,
      render: (duration) => (
        <>{durationHandler(duration)}</>
      )
    },
    {
      title: '标记选择题正确率',
      dataIndex: 'signAccuracy',
      hideInSearch: true,
      render: (signAccuracy, record) => (<>{record.signAccuracy ? (signAccuracy * 100).toFixed(1) + '%' : '-'}</>)
    },
    {
      title: '互动课件正确率',
      dataIndex: 'interactAccuracy',
      hideInSearch: true,
      render: (interactAccuracy, record) => (<>{record.interactAccuracy ? (interactAccuracy * 100).toFixed(1) + '%' : '-'}</>)
    },
    {
      title: '查看报告',
      hideInSearch: true,
      dataIndex: 'option',
      render: (_: any, recore: any) => {
        return <a target="_blank" href={`/web/gospirit_webview/study_report?token=${localStorage.getItem('token')}&uid=${recore.uid}&classroomId=${classroomId}`} rel="noreferrer">查看学习报告</a>
      }
    },
  ];



  return (
    <PageContainer>

      <ProTable<{}>
        headerTitle="数据列表"
        actionRef={actionRef}
        rowKey="key"
        request={async params => {
          params.uid = uid
          delete params.key
          const msg = await queryRule({
            classroomId,
            ...params,
            pageNum: params.current
          })
          setClassName(msg.data.classroomName)
          return {
            data: msg.data.users,
            success: true,
            total: msg.data.count
          }
        }}
        // onSubmit={async params => {
        //   params.uid = uid
        //   console.log(params)
        //   const msg = await queryRule({
        //     classroomId,
        //     ...params,
        //     pageNum: 9999,
        //     pageSize:20
        //   })

        //   return {
        //     data: msg.data.users,
        //     success: true,
        //     total: msg.data.count
        //   }
        // }}
        onReset={() => {
          window.location.reload()
        }}
        columns={columns}
        toolBarRender={
          (data: any) => (
            [
              <Alert message={`条目名称 : ${className}`} type="info" />,
              <Button key="primary" type="primary" onClick={() => { classroomExportHandler(className) }}>
                导出条目训练情况
              </Button>
            ]
          )
        }

      />
    </PageContainer>
  );
};

export default TableList;
